//
//  XJShopListViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/15.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJShopListViewController.h"
#import "XJShopDetailViewController.h"
#import "XJZPQSearchWYViewController.h"//7-4 宅配圈搜索

//view
#import "XJShopListItem.h"
#import "RBRefreshFooter.h"
#import "RBRefreshHeader.h"


//model
#import "XJShopListModel.h"

@interface XJShopListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic, strong) UICollectionView *clv;
@property(nonatomic, strong) NSMutableArray <XJShopListModel *>*dataArray;

/**下拉刷新*/
@property(nonatomic, assign) NSInteger page;
@end

@implementation XJShopListViewController

#pragma mark - 一 lazy
- (UICollectionView *)clv {
    if (!_clv) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        _clv = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _clv.delegate = self;
        _clv.dataSource = self;
        _clv.backgroundColor = [UIColor whiteColor];
        
        
        UINib *nib = [UINib nibWithNibName:@"XJShopListItem" bundle:nil];
        [_clv registerNib:nib forCellWithReuseIdentifier:@"XJShopListItem"];
    }
    return _clv;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark - 二 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self requestShopListData];
    
    [self setupView]; // 方法一定要记得调用。
    [self setupNav];
    
    [self setupRefresh];
    
    
}

- (void)setupNav {
    self.navigationItem.title = @"宅配圈";

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(rightSearchAction)];
}

- (void)rightSearchAction {
    [JRToast showWithText:@"搜索"];
    
    XJZPQSearchWYViewController *zpqSerachVC = [XJZPQSearchWYViewController suspendXJZPQSearchVYView];
    
    [self.navigationController pushViewController:zpqSerachVC animated:YES];
}

- (void)setupView {
    self.clv.frame = CGRectMake(0, 0, KWidth,KHeight - kStatusBarAndNavigationBarHeight);
    [self.view addSubview:self.clv];
}

- (void)setupRefresh {
    
    
    self.page = 1;
    
    self.clv.mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestShopListData)];
    
    self.clv.mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestLoadMoreData)];
}

#pragma mark - 三 UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    XJShopListItem *shopListItem = [collectionView dequeueReusableCellWithReuseIdentifier:@"XJShopListItem" forIndexPath:indexPath];
    
    shopListItem.model = self.dataArray[indexPath.row];
    return shopListItem;
}


#pragma mark -  UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    XJShopDetailViewController *shopdetailVC = [XJShopDetailViewController new];
    
    shopdetailVC.shopId = self.dataArray[indexPath.row].shopId;
    
    [self.navigationController pushViewController:shopdetailVC animated:YES];
}

#pragma mark - 三-2 UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat itemW = (KWidth - 32)/ 2;// 8*4 = 32
    return CGSizeMake(itemW, itemW * 1.2);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(20, 8, 20, 8);
}

#pragma mark - 四 网络请求
- (void)requestShopListData {
//    NSString *lat = @"30.194859";
//    NSString *lng = @"120.189506";
    NSString *lat = self.lat;
    NSString *lng = self.lng;

    
    
    self.page = 1;
    NSString *page = [NSString stringWithFormat:@"%ld",self.page];

    if (self.dataArray.count) {
        [self.dataArray removeAllObjects];
    }
    
    [self rb_showHub];
    
    [XJHttpTool requestShopListWithLat:lat lng:lng page:page successH:^(id responseObjc) {
        
        [self.clv.mj_header endRefreshing];
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            NSArray *listsArr = responseObjc[@"data"][@"lists"];
            
            for (NSDictionary *dic in listsArr) {
                XJShopListModel *model = [XJShopListModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.clv reloadData];
            });
            
            XJLog(@"数据源个数:%ld -- %@",self.dataArray.count,self.dataArray);
        }
        [self rb_hideHub];
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
        [self rb_hideHub];
        [self.clv.mj_header endRefreshing];
    }];
}

- (void)requestLoadMoreData {
    NSString *lat = @"30.194859";
    NSString *lng = @"120.189506";
    
    self.page++;
    NSString *page = [NSString stringWithFormat:@"%ld",self.page];
    
    [self rb_showHub];
    
    [XJHttpTool requestShopListWithLat:lat lng:lng page:page successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        if ([code isEqualToString:@"0"]) {

            NSArray *listsArr = responseObjc[@"data"][@"lists"];
            if (listsArr.count) {
                for (NSDictionary *dic in listsArr) {
                    XJShopListModel *model = [XJShopListModel mj_objectWithKeyValues:dic];
                    [self.dataArray addObject:model];
                }
                
                [self.clv.mj_footer endRefreshing];
            }else {
                [self.clv.mj_footer endRefreshingWithNoMoreData];
            }
           
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.clv reloadData];
            });
        }else {
            [self.clv.mj_footer endRefreshingWithNoMoreData];
        }
        [self rb_hideHub];
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
        
        [self.clv.mj_footer endRefreshingWithNoMoreData];
        [self rb_hideHub];
    }];
}
#pragma mark - 私有方法
- (void)rb_showHub {
    [MBProgressHUD showHUDAddedTo:self.clv animated:YES];
}

- (void)rb_hideHub{
    [MBProgressHUD hideAllHUDsForView:self.clv animated:YES];
}

@end
